﻿using AutoMapper;
using BasicInformationCommon.API.BasicInformationCommons.Materiales;
using ERPSystem.Common.Domains.Material;
using ERPSystem.Common.Domains.supplier;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using System.Linq;

namespace BasicInformationCommon.API.BasicInformationCommons.Suppliers
{
    public class SuppliersSearchHander : IRequestHandler<SuppliersSearchCommand, ResultPage<SuppliersDTO>>
    {
        private readonly IBaseRepository<Supplier> SuppliersRe;
        private readonly IBaseRepository<MaterialCascade> MaterialCascadeRe;
        public SuppliersSearchHander(IBaseRepository<Supplier> SuppliersRe, IBaseRepository<MaterialCascade> MaterialCascadeRe)
        {
            this.SuppliersRe = SuppliersRe;
            this.MaterialCascadeRe = MaterialCascadeRe;
        }

        public async Task<ResultPage<SuppliersDTO>> Handle(SuppliersSearchCommand request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<SuppliersDTO>() { Code = (int)CommonErrorCode.Search, TotalCount = 0, PageCount = 0 };
            try
            {
                var materialInformation = await (await MaterialCascadeRe.GetAll()).ToListAsync();
                var supplier = await (await SuppliersRe.GetAll()).ToListAsync();
                var cc = (from a in supplier
                          from value in a.MaterialTypeName.Split(',')
                          join b in materialInformation on int.Parse(value) equals b.MaterialTypeId
                          group new { a, b } by new { a.SupplierName, a.SupplierId, a.SupplierAbbreviation, a.SupplierAlias, a.BusinessContact, a.CompanyAddress, a.Phone } into c
                          select new SuppliersDTO()
                          {
                              SupplierId = c.Key.SupplierId,
                              SupplierName = c.Key.SupplierName,
                              SupplierAbbreviation = c.Key.SupplierAbbreviation,
                              SupplierAlias = c.Key.SupplierAlias,
                              BusinessContact = c.Key.BusinessContact,
                              CompanyAddress = c.Key.CompanyAddress,
                              Phone = c.Key.Phone,
                              MaterialTypeName = string.Join(",", c.Select(x => x.b.MaterialTypeName)),
                              MaterialTypeIds = string.Join(",", c.Select(x => x.b.MaterialTypeId))
                          }).ToList();
                if (!string.IsNullOrEmpty(request.SupplierName))
                {
                    cc = cc.Where(x => x.SupplierName.Contains(request.SupplierName)).ToList();
                }
                if (!string.IsNullOrEmpty(request.BusinessContact))
                {
                    cc = cc.Where(x => x.BusinessContact.Contains(request.BusinessContact)).ToList();
                }
                if (request.MaterialTypeName > 0)
                {
                    cc = cc.Where(x => x.MaterialTypeIds.Contains(request.MaterialTypeName.ToString())).ToList();
                }
                result.TotalCount = cc.Count;
                result.PageCount = (int)Math.Ceiling((result.TotalCount * 1.0) / request.PageSize);
                cc = cc.OrderByDescending(c => c.SupplierId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = cc;
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
